<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>socket-test</title>
  <link rel="stylesheet" href="./src/css/reset.css">
  <script src="./src/js/vue.min.js"></script>
  <script src="./src/js/socket.io.js"></script>
</head>

<body>
  <div id="app">
    <h3>socket--test</h3>
    <ul v-show="list">
      <li v-for="(item, index) in list" :key="index">name：{{item.username}} ---- text ：{{item.text}}</li>
    </ul>
    <br>
    <input type="text" v-model="text" @keydown.13="onsubmit">
    <input type="button" value="提交" @click="onsubmit">
  </div>
</body>
<script>
  window.onload = function () {
    var appVue = new Vue({
      el: '#app',
      data: {
        socket: io.connect('http://192.168.1.214:8080'),
        username: null,
        list: [],
        text: ''
      },
      created() {
        this.username = prompt('你的名字');
        this.socket.on('broadcast', function (data) {
          // if (data.login) {
          //   appVue.list.push(data)
          // }
          appVue.list.push(data)
        });
        this.socket.on('reconnect', function () {
          console.log("重新连接到服务器");
        });
      },
      methods: {
        onsubmit: function () {
          if (this.text == '') {
            alert('输入不能为空')
            return
          }
          console.log(this.socket.id);
          this.socket.emit('say', { username: this.username, user_id: this.socket.id, text: this.text });
          // this.list.push({ username: this.username, user_id: this.socket.id, text: this.text })
          this.text = ''
        }
      },
      watch: {
        username: function () {
          this.socket.emit('login', { username: this.username, user_id: this.socket.id });
        }
      }
    })

  }
</script>

</html>